package com.xyx.www;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

class Student {
	private String stuName;
	private int stuAge;

	public Student(String stuName, int stuAge) {
		super();
		this.stuName = stuName;
		this.stuAge = stuAge;
	}

	public String getStuName() {
		return stuName;
	}

	public void setStuName(String stuName) {
		this.stuName = stuName;
	}

	public int getStuAge() {
		return stuAge;
	}

	public void setStuAge(int stuAge) {
		this.stuAge = stuAge;
	}

	@Override
	public String toString() {
		return "Student [stuName=" + stuName + ", stuAge=" + stuAge + "]";
	}

}

public class Test0806Ioobject {

	public static void main(String[] args) {
		test01();
	}

	private static void test01() {
		Student stu = new Student("小池", 99);
		// 写入到文件中
		String filePath = writeObject(stu, "stuSuper");
		// 从文件中读取出来
		Object obj = readObject(filePath);
		// 向下转型为Student类型
		Student stu1 = (Student) obj;
		// 比较将对象存入文件就再取出是否为同一个对象
		System.out.println("s"
				+ "tu==stu1" + (stu == stu1));
		//System.out.println(stu1.getStuAge()+stu1.getStuName());
		System.out.println(stu1);

	}

	private static Object readObject(String filePath) {
		Object obj = null;
		try {
			// 创建Objectinput对象实例
			ObjectInputStream in = new ObjectInputStream(new FileInputStream(filePath));
			// 读入对象
			
			obj = in.readObject();
			// 关闭资源
			in.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.getMessage();
		}
		//返回此对象
		return obj;

	}

	private static String writeObject(Object obj, String fileName) {
		// 创建文件地址
		String filePath = "D:\\JAVA\\JavaTools\\IoObject\\" + fileName + System.currentTimeMillis() + ".dat";
		try {
			// 创建ObjectOutputStream实例对象
			ObjectOutputStream obs = new ObjectOutputStream(new FileOutputStream(filePath));
			// 将obj对象写出到文件中
			obs.writeObject(obj);
			// 清空
			obs.flush();
			// 关闭资源
			obs.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return filePath;
	}
}
